/**
 * 主从表配置服务JS-DataService.jsp
 */

//项目路径
var strPath = window.document.location.pathname;
//var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
var postPath = "/gdp";

var masterServer = masterServer || {};
masterServer.prototype = {
    init: function () {//初始化
        masterServer.prototype.bindInit();//数据初始化
        $("#btn_save").on("click", masterServer.prototype.msaveData);//主表保存信息
        $("#a_tab_d").on("click", masterServer.prototype.setDetailtable);//设置从表配置
        $("#btn_dsave").on("click", masterServer.prototype.dsaveData);//从表保存信息
        $("#btn_detailEndit").on("click", masterServer.prototype.updateMasterDetial);//从表修改信息
        $("#btn_detailDel").on("click", masterServer.prototype.delMasterDetial);//删除从表信息
        $("#removeServer").on("click", masterServer.prototype.delMasterAll);//删除主从表服务
        $("#a_tab_1_3").on("click", masterServer.prototype.setMasterQueryField);//设置主表查询列
        $("#btn_back").on("click", masterServer.prototype.goBlack);//返回列表
        masterServer.prototype.showFieldinit();//主表显示列初始化
        $("#dtconfigID").select2();
        //$("#ddtconfigid").select2();
        //新增显示字段Modul关闭监听事件
        $("#FieldModul").on('hidden.bs.modal', function (e) {
            $("#tb_showfieldList").bootstrapTable('refresh');
            $("#tb_detail").bootstrapTable('refresh');
        });

        //是否缓存点击事件
        $("#sysCatch1").click(function () {
            $("#catchtime").attr("readonly", "readonly");
            $("#catchtime").val("0");
        });
        $("#sysCatch2").click(function () {
            $("#catchtime").removeAttr("readonly");
        });
    },
    bindInit: function () {//数据初始化
        //绑定数据源标识
        $.ajax({
            type: 'POST',
            // url: postPath + '/system/masterDetail/getAllDataSource',
            url: postPath + '/system/sysProject/getProjectToDataSource?pcode=' + GetQueryString("projectid"),
            async: false,
            success: function (res) {
                $("#dbkey").append('');
                var strtxt = "<option value=''>请选择</option>";
                if (res.success) {
                    $.each(res.data, function (i, e) {
                        strtxt += "<option value='" + e.dbKey + "'>" + e.dbMark + "(" + e.dbKey + ")" + "</option>";
                    });
                }
                $("#dbkey").html(strtxt);
            },
            error: function () {
                showMsg("获取数据源失败!", "error");
                // bootbox.alert("获取数据源失败!");
            }
        });


        $("#dbkey").click(function () {
            masterServer.prototype.getTableData($("#dbkey").val());
        });

        if ($("#hid_operate").val() == "edit") {
            $("#isedit").val("1");
            $.ajax({
                type: 'POST',
                url: postPath + '/system/masterDetail/getCfgExtmasterByguid',
                data: {guid: $("#hid_guid").val()},
                success: function (data) {
                    if (data != null) {
                        masterServer.prototype.getTableData(data.dbKey);
                        $("#guid").attr("readonly", "readonly");
                        $("#guid").val(data.guid);
                        $("#serviceName").val(data.servicename);
                        $("#dbkey").val(data.dbKey);
                        $("#dtconfigID").val(data.dtConfigId).trigger("change");
                        $("#remark").val(data.remark);
                        $("#hid_guid").val(data.guid);
                        $("input:radio[name='radioSysCatch'][value=" + data.syscatch + "]").attr("checked", true);
                        $("input:radio[name='radioPagintion'][value=" + data.ispagination + "]").attr("checked", true);
                        $("#catchtime").val(data.catchtime);
                    }
                }
            });
        } else if ($("#hid_operate").val() == "add") {
            $("#isedit").val("0");
        }
    },
    getTableData: function (dbkey) {//通过dbkey查询数据库表
        $("#dtconfigID").select2("val", "");
        $.ajax({
            type: 'POST',
            url: postPath + '/system/masterDetail/getTabledatabydbkey',
            data: {dbkey: dbkey},
            async: false,
            success: function (data) {
                if (data != null) {
                    $("#dtconfigID").html("");
                    $("#dtconfigID").append("<option value=''>请选择</option>");
                    $.each(data, function (i, e) {
                        $("#dtconfigID").append("<option value='" + e.dtConfigId + "'>" + e.dtNameCn + "</option>");
                    });
                }
            },
            error: function () {
                showMsg("获取数据库表失败,请刷新后重试!", "error");
                // bootbox.alert("获取数据库表失败,请刷新后重试!");
            }
        });
    },
    validateInfo: function () {
        if ($("#guid").val() == "") {
            $("#errorInfo").html("服务ID不能为空!");
            return false;
        } else {
            if ($("#isedit").val() == "0") {
                var result = true;
                $.ajax({
                    type: 'POST',
                    url: postPath + '/system/masterDetail/isExistGuid',
                    data: {guid: $("#guid").val()},
                    async: false,
                    success: function (data) {
                        result = data;
                    }
                });
                if (result == false) {
                    $("#errorInfo").html("服务ID以存在!");
                    return false;
                } else {
                    $("#errorInfo").html("");
                }
            }
        }
        if ($("#serviceName").val() == "") {
            $("#errorInfo").html("服务名称不能为空!");
            return false;
        } else {
            $("#errorInfo").html("");
        }

        if ($("#dbkey").val() == "") {
            $("#errorInfo").html("数据库标识不能为空!");
            return false;
        } else {
            $("#errorInfo").html("");
        }

        if ($('input:radio[name="radioSysCatch"]:checked').val() == 1) {
            if ($("#catchtime").val() == "") {
                $("#errorInfo").html("缓存时间不能为空!");
                return false;
            } else {
                var cachetime = $("#catchtime").val();
                var re = /^[1-9]+[0-9]*]*$/; //判断字符串是否为数字
                if (!re.test($("#catchtime").val())) {
                    $("#errorInfo").html("缓存时间为正整数!");
                    return false;
                } else if (cachetime > 100) {
                    $("#errorInfo").html("缓存时间应小于100分钟!");
                    return false;
                }
            }
        } else {
            $("#errorInfo").html();
        }

        if ($("#dtconfigID").val() == "") {
            $("#errorInfo").html("请选择主表!");
            return false;
        } else {
            $("#errorInfo").html("");
        }
        return true;
    },
    msaveData: function () {//保存主表信息
        var validate = masterServer.prototype.validateInfo();
        if (validate) {
            var temp = {
                guid: $("#guid").val(),
                servicename: $("#serviceName").val(),
                dbKey: $("#dbkey").val(),
                dtConfigId: $("#dtconfigID").val(),
                remark: $("#remark").val(),
                syscatch: $('input:radio[name="radioSysCatch"]:checked').val(),
                ispagination: $('input:radio[name="radioPagintion"]:checked').val(),
                responseMode: $('input:radio[name="radioResponseMode"]:checked').val(),
                catchtime: $('#catchtime').val(),
                pcode: $("#hid_projectid").val(),
                servicetype: $("#hid_servertype").val()
            };
            var saveurl = "";
            if ($("#isedit").val() == "0") {
                saveurl = postPath + '/system/masterDetail/insertMasterData';
            } else if ($("#isedit").val() == "1") {
                saveurl = postPath + '/system/masterDetail/updateMasterData';
            }
            $.ajax({
                type: 'POST',
                url: saveurl,
                async: false,
                data: JSON.stringify(temp),
                dataType: 'json',
                contentType: "application/json",
                success: function (res) {
                    if (res > 0) {
                        $("#hid_guid").val($("#guid").val());
                        $("#isedit").val("1");
                        // bootbox.alert("保存成功!");
                        showMsg("保存成功!", "success");
                    } else {
                        // bootbox.alert("保存失败!");
                        showMsg("保存失败!", "error");
                    }
                }
            });
        }
    },
    delMasterAll: function () {//删除主从表服务(包括从表数据)
        if ($("#hid_guid").val() == "") {
            showMsg("请先选择服务!", "warning");
            // bootbox.alert("请先选择服务");
            return;
        }
        bootbox.confirm("确认删除服务：" + $("#hid_guid").val() + "?", function (result) {
            if (!result) {
                return;
            }
            $.ajax({
                type: 'POST',
                url: postPath + '/system/masterDetail/deleteMasterData',
                data: {guid: $("#hid_guid").val()},
                success: function (res) {
                    if (res > 0) {
                        masterServer.prototype.mcleanData();
                        showMsg("删除成功!", "success");
                        // bootbox.alert("删除成功!");
                    } else {
                        // bootbox.alert("删除失败,请刷新后重试!");
                        showMsg("删除失败,请刷新后重试!!", "error");
                    }
                }, error: function () {
                    // bootbox.alert("删除失败,请刷新后重试!");
                    showMsg("删除失败,请刷新后重试!!", "error");
                }
            });
        });
    },
    mcleanData: function () {//清空主表配置信息
        $("#guid").val("");
        $("#serviceName").val("");
        $("#dbkey").val("");
        $("#dtconfigID").html("");
        $("#remark").val("");
        $("#isedit").val("");
        $("#catchtime").val("");
        $("#hid_guid").val("");
        $("#guid").removeAttr("readonly");
    },
    getgo: function () {//初始化tab选项卡
        $('#myTab a[href="#tab_1_1_1"]').tab('show');
        $('#tab_right a[href="#tab_1_1"]').tab('show');
    },
    setDetailtable: function () {//设置从表配置信息
        var hidguid = $("#hid_guid").val();
        if (hidguid == "") {
            // bootbox.alert("请先设置主表信息配置!");
            showMsg("请先设置主表信息配置!", "warning");
            setTimeout(masterServer.prototype.getgo, 200);
            return;
        }

        var fielddata = masterServer.prototype.getFieldbyguid(hidguid);
        if (fielddata != null && fielddata != "") {
            $("#mfiled").html("");
            $("#mfiled").append("<option value=''>请选择主表字段</option>");
            $.each(fielddata, function (i, e) {
                $("#mfiled").append("<option value='" + e.key + "'>" + e.value + "</option>");
            });
        }

        var tabledata = masterServer.prototype.getTableByguid(hidguid);
        if (tabledata != null && tabledata != "") {
            $("#ddtconfigid").html("");
            $("#ddtconfigid").append("<option value=''>请选择</option>");
            $.each(tabledata, function (i, e) {
                $("#ddtconfigid").append("<option value='" + e.dtConfigId + "'>" + e.dtNameCn + "</option>");
            });
        }

        $("#ddtconfigid").change(function () {
            var dfield = masterServer.prototype.getFieldbydtconfig($("#ddtconfigid").val());
            if (dfield != null && dfield != "") {
                $("#dfiled").html("");
                $("#dfiled").append("<option value=''>请选择从表字段</option>");
                $.each(dfield, function (i, e) {
                    $("#dfiled").append("<option value='" + e.key + "'>" + e.value + "</option>");
                });
            }
        });

        masterServer.prototype.getMasterDetailTable();

    },
    goBlack: function () {//返回列表
        window.location.href = postPath + "/prjService/index";
    },
    getFieldbyguid: function (hidguid) {//通过主表服务id查询表字段信息
        var fielddata = "";
        $.ajax({
            type: 'POST',
            url: postPath + '/system/masterDetail/getFieldbymasterguid',
            data: {guid: hidguid},
            async: false,
            success: function (data) {
                fielddata = data;
            }
        });
        return fielddata;
    },
    getFieldbydtconfig: function (dtconfigid) {//通过表标识查询其字段信息
        var fielddata = "";
        $.ajax({
            type: 'POST',
            url: postPath + '/system/masterDetail/getFieldbydtconfigid',
            data: {dtConfigid: dtconfigid},
            async: false,
            success: function (data) {
                fielddata = data;
            }
        });
        return fielddata;
    },
    getTableByguid: function (hidguid) {//通过主表服务id查询该数据源所有表信息
        var tabledata = "";
        $.ajax({
            type: 'POST',
            url: postPath + '/system/masterDetail/getTablebyMasterguid',
            data: {guid: hidguid},
            async: false,
            success: function (data) {
                tabledata = data;
            }
        });
        return tabledata;
    },
    dsaveData: function () {//保存从表信息
        var dvalidateResult = masterServer.prototype.dvalidateData();
        if (dvalidateResult) {
            var masterdetail = {
                guid: $("#hid_dguid").val(),
                mguid: $("#hid_guid").val(),
                mfield: $("#mfiled").val(),
                dtConfigId: $("#ddtconfigid").val(),
                dfield: $("#dfiled").val(),
                remark: $("#dremark").val(),
                slaveTableCustomAlias: $("#slaveTableCustomAlias").val()
            };
            var saveUrl = "";
            if ($("#hid_dguid").val() == "") {
                saveUrl = postPath + '/system/masterDetail/insertMasterDetail';
            } else {
                saveUrl = postPath + '/system/masterDetail/updateMasterDetail';
            }
            $.ajax({
                type: 'POST',
                url: saveUrl,
                async: false,
                data: JSON.stringify(masterdetail),
                dataType: 'json',
                contentType: "application/json",
                success: function (res) {
                    if (res > 0) {
                        masterServer.prototype.cleanDetailData();
                        $("#tb_detail").bootstrapTable('refresh');
                        $('#tab_left a[href="#tab_2_1"]').tab('show');
                        // bootbox.alert("保存成功!");
                        showMsg("保存成功!", "success");
                        $("#slaveTableModule").modal("hide");
                    } else {
                        // bootbox.alert("保存失败!");
                        showMsg("保存失败!", "error");
                        $("#slaveTableModule").modal("hide");

                    }
                }
            });

        }
    },
    dvalidateData: function () {//验证从表信息
        if ($("#mfiled").val() == "") {
            $("#derrorInfo").html("请选择主表关联字段!");
            return false;
        } else {
            $("#derrorInfo").html("");
        }

        if ($("#ddtconfigid").val() == "") {
            $("#derrorInfo").html("请选择从表!");
            return false;
        } else {
            $("#derrorInfo").html("");
        }

        if ($("#dfiled").val() == "") {
            $("#derrorInfo").html("请选择从表关联字段!");
            return false;
        } else {
            $("#derrorInfo").html("");
        }
        return true;

    },
    cleanDetailData: function () {//清空从表信息
        $("#hid_dguid").val("");
        $("#mfiled").val("");
        $("#ddtconfigid").val("");
        $("#dfiled").html("");
        $("#dremark").val("");
    },
    getMasterDetailTable: function () {//查询从表信息
        $("#tb_detail").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/system/masterDetail/getExtMasterDetailBymguid',
            detailView: true,//父子表
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            cache: false, // 是否使用缓存
            singleSelect: true,
            queryParams: {mguid: $("#hid_guid").val()},
            uniqueId: "guid", // 每一行的唯一标识
            columns: [{
                field: 'state',
                title: '选择列',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                title: '主表服务ID',
                field: 'mguid',
                align: 'center',
                valign: 'middle'
            }, {
                title: '主表关联字段',
                field: 'mfieldCh',
                align: 'center',
                valign: 'middle'
            }, {
                title: '从表名称',
                field: 'dtConfigCh',
                align: 'center',
                valign: 'middle'
            }, {
                title: '从表关联字段',
                field: 'dfieldCh',
                align: 'center',
                valign: 'middle'
            }, {
                title: '表别名',
                field: 'slaveTableCustomAlias',
                align: 'center',
                valign: 'middle'
            }, {
                title: '备注',
                field: 'remark',
                align: 'center',
                valign: 'middle'
            }, {
                title: '操作',
                field: 'option',
                align: 'center',
                valign: 'middle',
                formatter: function (value, row, index) {
                    var operateTags = "";
                    operateTags += "<a href='javascript:;' onclick='masterServer.prototype.eventAddDetailShowField(\"" + row.guid + "\")' class='btn btn-default btn-sm'><i class='fa fa-plus'></i>新增显示列</a>";
                    //operateTags += "<a href='javascript:;' onclick='masterServer.prototype.eventUpdateDetailShowField(\"" + row.guid + "\")' class='btn btn-default btn-sm'><i class='fa fa-plus'></i>修改显示列</a>";
                    return operateTags;
                }
            }],
            onExpandRow: function (index, row, $detail) {
                var serviceId = row.mguid
                var serviceType = 2;
                var masterDetailId = row.guid;
                var cur_table = $detail.html('<table></table>').find('table');
                $(cur_table).bootstrapTable({
                    url: postPath + '/system/showfield/getShowFieldList',
                    method: 'get',
                    queryParams: {serviceId: serviceId, serviceType: serviceType, masterDetailId: masterDetailId},
                    clickToSelect: true,
                    uniqueId: "guid",
                    columns: [{
                        title: '字段名称',
                        field: 'fieldname',
                        align: 'center',
                        valign: 'middle'
                    }, {
                        title: '自定义字段名称',
                        field: 'customAlias',
                        align: 'center',
                        valign: 'middle',
                        width: '200px',
                        editable: true
                    }, {
                        title: '字段标题名称',
                        field: 'fieldnameCn',
                        align: 'center',
                        valign: 'middle'
                    },{
                        title: '自定义字段标题名称',
                        field: 'customFieldNameAlias',
                        align: 'center',
                        valign: 'middle',
                        width: '200px',
                        editable: true
                    }, {
                        title: '字段类型',
                        field: 'fieldtype',
                        align: 'center',
                        valign: 'middle'
                    }, {
                        title: '字段显示顺序',
                        field: 'showorder',
                        align: 'center',
                        width: '100px',
                        valign: 'middle',
                        editable: true
                    }, {
                        title: '操作',
                        align: 'center',
                        valign: 'middle',
                        sortable: false,
                        formatter: function (value, row, index) {
                            var strtd = "";
                            strtd += " <a href='javascript:;' onclick='masterServer.prototype.eventDelDetailShowField(\"" + row.guid + "," + row.fieldname+ "\");' class='btn btn-default btn-sm'><i class='fa fa-remove'></i> </a>";
                            return strtd;
                        }
                    }],
                    onEditableSave: function (field, row, oldValue, $el) {
                        var re = /^[1-9]+[0-9]*]*$/; //判断字符串是否为数字
                        if (!re.test(row.showorder)) {
                            // bootbox.alert("字段排序值为正整数!");
                            showMsg("字段排序值为正整数!", "warning");
                            return false;
                        } else if (row.showorder > 100) {
                            // bootbox.alert("字段排序值不宜过大!");
                            showMsg("字段排序值不宜过大!", "warning");
                            return false;
                        }
                        var temp = {
                            guid: row.guid,
                            serviceid: $("#hid_guid").val(),
                            masterdetailid: row.masterdetailid,
                            showorder: row.showorder,
                            servicetype: 2,
                            customAlias: row.customAlias,
                            customFieldNameAlias: row.customFieldNameAlias

                        };
                        $.ajax({
                            type: 'POST',
                            url: postPath + '/system/showfield/updateShowField',
                            async: false,
                            data: JSON.stringify(temp),
                            dataType: 'json',
                            contentType: "application/json",
                            success: function (data) {
                                // bootbox.alert("修改成功!");
                                showMsg("修改成功!", "success");
                            }
                        });

                    }
                });
            }
        });

    },
    updateMasterDetial: function () {//修改从表信息
        var row = $('#tb_detail').bootstrapTable('getSelections');
        if (row == null || row == "") {
            // bootbox.alert("请选择一行!");
            //showMsg("请选择一行!", "warning");
            return;
        }
        $("#hid_dguid").val(row[0].guid);
        $("#mfiled").val(row[0].mfield);
        $("#ddtconfigid").val(row[0].dtConfigId);
        var fielddata = masterServer.prototype.getFieldbydtconfig(row[0].dtConfigId);
        if (fielddata != null && fielddata != "") {
            $("#dfiled").html("");
            $("#dfiled").append("<option value=''>请选择</option>");
            $.each(fielddata, function (i, e) {
                $("#dfiled").append("<option value='" + e.key + "'>" + e.value + "</option>");
            });
        }
        $("#dfiled").val(row[0].dfield);
        $("#dremark").val(row[0].remark);
        $("#slaveTableCustomAlias").val(row[0].slaveTableCustomAlias);
        $("#slaveTableModule").modal("show");
    },
    delMasterDetial: function () {//通过guid删除从表数据
        var row = $('#tb_detail').bootstrapTable('getSelections');
        if (row == null || row == "") {
            bootbox.alert("请选择一行!");
            //showMsg("请选择一行!", "warning");
            return;
        }

        var deleteFunction = function (result) {
            if (!result) {
                return;
            }
            $.ajax({
                type: 'POST',
                url: postPath + '/system/masterDetail/deleteMasterDetailbyguid',
                data: {guid: row[0].guid},
                success: function (res) {
                    if (res > 0) {
                        $("#tb_detail").bootstrapTable('refresh');
                        masterServer.prototype.cleanDetailData();
                        // bootbox.alert("删除成功!");
                        showMsg("删除成功!", "success");
                    }
                },
                error: function () {
                    // bootbox.alert("删除失败,请刷新后重试!");
                    showMsg("删除失败,请刷新后重试!", "error");
                }
            });
        };

        var message = row[0].dtConfigCh

        confirmDelete(message, deleteFunction);
    },
    eventAddDetailShowField: function (dguid) {//新增从表显示字段
        var frameSrc = postPath + "/showFieldList/index?serviceId=" + $("#hid_guid").val() + "&serviceType=2&masterDetailId=" + dguid + "&operateMethod=add";
        $("#fieldIframe").attr("src", frameSrc);
        $("#FieldModul").modal('show');
    },
    eventUpdateDetailShowField: function (dguid) {//从表显示字段
        var rowList = $("#tb_showfieldList").bootstrapTable("getSelections");

        var jsonDataList = encode_utf8(JSON.stringify(rowList));

        // here is add selection convert json parameter
        var frameSrc = postPath + "/showFieldList/index?serviceId=" + $("#hid_guid").val() + "&serviceType=2&masterDetailId=" + dguid + "&operateMethod=update&jsonDataList=" + jsonDataList;
        $("#fieldIframe").attr("src", frameSrc);
        $("#FieldModul").modal('show');
    },
    eventDelDetailShowField: function (rowObject) {//删除从表显示列
        console.log("luowen rowObject", rowObject )
        var rowObjectContent = rowObject.split(",")
        var ddguid = rowObjectContent[0]
        var fieldname = rowObjectContent[1];
        var deleteFunction = function (result) {
            if (result == false)
                return;
            $.ajax({
                url: postPath + '/system/showfield/deleteShowField',
                type: 'POST',
                data: {guids: ddguid},
                success: function (res) {
                    if (res > 0) {
                        // bootbox.alert("删除成功!");
                        showMsg("删除成功!", "success");
                        $('#tb_detail').bootstrapTable('refresh');
                    } else {
                        // bootbox.alert("删除失败!");
                        showMsg("删除失败!", "error");
                    }
                },
                error: function () {
                    // bootbox.alert("删除失败!");
                    showMsg("删除失败!", "error");
                }
            });
        };

        confirmDelete(fieldname, deleteFunction);
    },
    setMasterQueryField: function () {//主表查询字段配置初始化
        if ($("#hid_guid").val() == "") {
            // bootbox.alert("请先设置主表信息配置!");
            showMsg("请先设置主表信息配置!", "warning");
            setTimeout(masterServer.prototype.getgo, 200);
            return;
        }
        var frameSrc = postPath + "/queryConditionConfig/index?serviceId=" + $("#hid_guid").val() + "&serviceType=2&grade=";
        $("#queryIframe").attr("src", frameSrc);
    },
    showFieldinit: function () {//主表显示列初始化
        masterServer.prototype.eventShowFieldclick();
        masterServer.prototype.eventAddShowField();
        masterServer.prototype.eventUpdateShowField();

        masterServer.prototype.eventDelShowField();

        // here is init slave table
        masterServer.prototype.eventAddSlaveTable();
        masterServer.prototype.eventHiddenSlaveTableModule();
    },
    eventShowFieldclick: function () {//主表显示列配置选项卡单机事件
        $("#a_tab_1_2").click(function () {
            if ($("#hid_guid").val() == "") {
                // bootbox.alert("请先设置主表信息配置!");
                showMsg("请先设置主表信息配置!", "warning");
                setTimeout(masterServer.prototype.getgo, 200);
                return;
            }
            masterServer.prototype.getShowFieldList();
        });

    },
    getShowFieldList: function () {//查询主表显示列列表
        //加载数据
        $("#tb_showfieldList").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/system/showfield/getShowFieldList',
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            queryParams: {serviceId: $("#hid_guid").val(), serviceType: "2", masterDetailId: ""},
            uniqueId: "guid", // 每一行的唯一标识
            columns: [{
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                title: '服务ID',
                field: 'serviceid',
                align: 'center',
                valign: 'middle',
                visible: false
            }, {
                title: '字段名称',
                field: 'fieldname',
                align: 'center',
                valign: 'middle'
            }, {
                title: '自定义字段名称',
                field: 'customAlias',
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段标题名称',
                field: 'fieldnameCn',
                align: 'center',
                valign: 'middle'
            }, {
                title: '自定义字段标题名称',
                field: 'customFieldNameAlias',
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段类型',
                field: 'fieldtype',
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段显示顺序',
                field: 'showorder',
                align: 'center',
                width: '100px',
                valign: 'middle'
            }]
            // onCheck: editShowField,
            // onUncheck: saveShowField
        });

        //修改显示字段信息
        function editShowField(row) {
            $("#tb_showfieldList").find("tr").each(function () {
                var trguid = $(this).attr("data-uniqueid");
                if (trguid == row.guid) {
                    var nRow = $(this);
                    var jqTds = $('>td', nRow);
                    jqTds[6].innerHTML = '<input style="width:60px !important;" id="touchspin_1" type="text" value="' + (row.showorder == null ? "0" : row.showorder) + '">';
                    jqTds[2].innerHTML = '<input style="width:160px" id="customAliasId" type="text" value="' + row.customAlias +  '">';
                    jqTds[4].innerHTML = '<input style="width:160px" id="customFieldNameAliasId" type="text" value="' + row.customFieldNameAlias +  '">';
                }
            });
            $("#touchspin_1").TouchSpin({
                verticalbuttons: true
            });
        }


        //保存修改显示字段信息
        function saveShowField(row) {
            $("#tb_showfieldList").find("tr").each(function () {
                var trguid = $(this).attr("data-uniqueid");
                if (trguid == row.guid) {
                    var nRow = $(this);
                    var jqTds = $('>td', nRow);
                    var showOrder = $('#touchspin_1').val();
                    var customAlias = $('#customAliasId').val()
                    var customFieldNameAlias = $('#customFieldNameAliasId').val()

                    var temp = {
                        guid: row.guid,
                        serviceid: $("#hid_guid").val(),
                        showorder: showOrder,
                        masterdetailid: '',
                        servicetype: 2,
                        customAlias: customAlias,
                        customFieldNameAlias: customFieldNameAlias
                    };
                    $.ajax({
                        type: 'POST',
                        url: postPath + '/system/showfield/updateShowField',
                        async: false,
                        data: JSON.stringify(temp),
                        dataType: 'json',
                        contentType: "application/json",
                        success: function (data) {
                            $("#tb_showfieldList").bootstrapTable('refresh');
                        }
                    });
                }
            });
        }

    },
    eventAddShowField: function () {//新增主表显示列事件

        $("#btn_showAdd").click(function () {
            var frameSrc = postPath + "/showFieldList/index?serviceId=" + $("#hid_guid").val() + "&serviceType=2&masterDetailId=&operateMethod=add";
            $("#fieldIframe").attr("src", frameSrc);
            $("#FieldModul").modal('show');
        });
    },
    eventUpdateShowField: function () {//新增主表显示列事件

        $("#btn_showUpdate").click(function () {
            var rowList = $("#tb_showfieldList").bootstrapTable("getSelections");
            var jsonDataList = encode_utf8(JSON.stringify(rowList));
            var frameSrc = postPath + "/showFieldList/index?serviceId=" + $("#hid_guid").val() + "&serviceType=2&masterDetailId="+ "&operateMethod=update&jsonDataList=" + jsonDataList;
            $("#fieldIframe").attr("src", frameSrc);
            $("#FieldModul").modal('show');
        });
    },

    eventAddSlaveTable: function(){
        $("#btn_showAddSlaveTable").click(function (){
            // here is provider slaveTableDialog show
            $("#slaveTableModule").modal("show");

        });
    },
    eventHiddenSlaveTableModule: function() {
        $("#slaveTableModule").modal("hide")

    },
    eventDelShowField: function () {//删除主表显示列事件
        $("#btn_showDel").click(function () {
            var row = $('#tb_showfieldList').bootstrapTable('getSelections');
            if (row == null || row == "") {
                bootbox.alert("请选择一行!");
                return;
            }

            // here show message
            var message = ""
            row.forEach(function(e, i){
                message += e.fieldname + ", " + e.fieldnameCn +"<br/>"
            })

            var deleteFunction = function (result) {
                if (result == false)
                    return;
                var keys = "";
                $.each(row, function (i, e) {
                    keys += e.guid + ",";
                });
                keys = keys.substring(0, keys.length - 1);
                $.ajax({
                    url: postPath + '/system/showfield/deleteShowField',
                    type: 'POST',
                    data: {guids: keys},
                    success: function (res) {
                        if (res > 0) {
                            // bootbox.alert("删除成功!");
                            showMsg("删除成功!","success");
                            $('#tb_showfieldList').bootstrapTable('refresh');
                        } else {
                            // bootbox.alert("删除失败!");
                            showMsg("删除失败!","error");
                        }
                    },
                    error: function () {
                        // bootbox.alert("删除失败!");
                        showMsg("删除失败!","error");
                    }
                });
            };

            confirmDelete(message, deleteFunction);
        });
    }

};

$(document).ready(function () {
    //获取参数
    $("#hid_servertype").val(GetQueryString("servertype"));//服务类型 添加使用
    $("#hid_operate").val(GetQueryString("operate")); //操作类型
    $("#hid_guid").val(GetQueryString("servercode"));//服务ID  修改使用
    $("#hid_projectid").val(GetQueryString("projectid"));//工程ID 添加修改预留
    var mserver = masterServer.prototype;
    mserver.init();
})

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//子页面调用父页面方法-关闭模态框
function closeModul() {
    $("#FieldModul").modal('hide');
}

function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}

function encode_utf8(s) {
  return encodeURIComponent(s);
}

function removeFinalChar(content){
    return content = content.substring(0, content.length - 1);
}

function confirmDelete(message, confirmFunction){
    var messageObj = {
        title: '确认删除？',
        message: message ,
        callback: confirmFunction
    }
    bootbox.confirm(messageObj);
}
